package com.cardone.platform.authority.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.authority.dto.RoleDto;
import com.cardone.platform.authority.dto.RolePermissionDto;
import com.cardone.platform.authority.service.AuthorityService;
import com.cardone.platform.authority.validator.RolePermissionValidator;
import com.cardone.platform.authority.validator.RoleValidator;
import com.cardone.platform.authority.vo.RoleVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 角色
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(RoleController.Paths.ROOT)
@Controller
public class RoleController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 消息
		 */
		message,

		/**
		 * 角色
		 */
		role,

		/**
		 * 角色与许可
		 */
		rolePermission;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 角色主界面
		 */
		index,

		/**
		 * 角色与许可编辑视图路径
		 */
		ROLE_PERMISSIONEdit("rolePermission/edit"),

		/**
		 * 角色与许可主界面视图路径
		 */
		ROLE_PERMISSIONIndex("rolePermission/index"),

		/**
		 * 角色与许可编辑视图路径
		 */
		ROLE_PERMISSIONNew("rolePermission/new"),

		/**
		 * 角色与许可查看编辑视图路径
		 */
		ROLE_PERMISSIONView("rolePermission/view"),

		/**
		 * 角色编辑视图路径
		 */
		ROLEEdit("role/edit"),

		/**
		 * 角色主界面视图路径
		 */
		ROLEIndex("role/index"),

		/**
		 * 角色编辑视图路径
		 */
		ROLENew("role/new"),

		/**
		 * 角色查看编辑视图路径
		 */
		ROLEView("role/view");

		/**
		 * 角色视图根目录
		 */
		public static final String ROOT = "/platform/authority/role/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 角色服务
	 */
	@Qualifier(AuthorityService.BEAN_ID)
	@Autowired(required = false)
	private AuthorityService authorityService;

	/**
	 * 角色与许可验证
	 */
	@Qualifier(RolePermissionValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator rolePermissionValidator;

	/**
	 * 角色验证
	 */
	@Qualifier(RoleValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator roleValidator;

	/**
	 * 角色：删除
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "role/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> roleDelete(final RoleVo roleVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getRoleService().deleteRoleByIds(roleVo.getRole());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 角色：编辑
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色编辑视图路径
	 */
	@RequestMapping(value = { "role/edit.html" }, method = RequestMethod.GET)
	public String roleEdit(final RoleVo roleVo, final Model model) {
		final RoleDto role = this.authorityService.getRoleService().findRoleById(roleVo.getRole());

		model.addAttribute(RoleController.models.role.name(), role);

		return RoleController.Paths.ROLEEdit.path();
	}

	/**
	 * 角色：主界面
	 * 
	 * @return 角色主界面视图路径
	 */
	@RequestMapping(value = { "role/index.html" })
	public String roleIndex() {
		return RoleController.Paths.ROLEIndex.path();
	}

	/**
	 * 角色：主界面分页查询
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "role/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> roleIndexPagination(final RoleVo roleVo) {
		final PaginationDto<RoleDto> rolePagination = this.authorityService.getRoleService().paginationRoleByCode(roleVo.getRole());

		final Map<String, Object> rolePaginationMap = Maps.newHashMap();

		rolePaginationMap.put(Constants.total.stringValue(), rolePagination.getTotalSize());
		rolePaginationMap.put(Constants.rows.stringValue(), rolePagination.getDataList());

		return rolePaginationMap;
	}

	/**
	 * 角色：新增
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色编辑视图路径
	 */
	@RequestMapping(value = { "role/new.html" }, method = RequestMethod.GET)
	public String roleNew(final RoleVo roleVo, final Model model) {
		model.addAttribute(RoleController.models.role.name(), roleVo.getRole());

		return RoleController.Paths.ROLENew.path();
	}

	/**
	 * 角色与许可：删除
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "rolePermission/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> rolePermissionDelete(final RoleVo roleVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getRoleService().deleteRolePermissionByIds(roleVo.getRolePermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 角色与许可：编辑
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色与许可编辑视图路径
	 */
	@RequestMapping(value = { "rolePermission/edit.html" }, method = RequestMethod.GET)
	public String rolePermissionEdit(final RoleVo roleVo, final Model model) {
		final RolePermissionDto rolePermission = this.authorityService.getRoleService().findRolePermissionById(
		        roleVo.getRolePermission());

		model.addAttribute(RoleController.models.rolePermission.name(), rolePermission);

		return RoleController.Paths.ROLE_PERMISSIONEdit.path();
	}

	/**
	 * 角色与许可：主界面
	 * 
	 * @return 角色与许可主界面视图路径
	 */
	@RequestMapping(value = { "rolePermission/index.html" })
	public String rolePermissionIndex() {
		return RoleController.Paths.ROLE_PERMISSIONIndex.path();
	}

	/**
	 * 角色与许可：主界面分页查询
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "rolePermission/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> rolePermissionIndexPagination(final RoleVo roleVo) {
		final PaginationDto<RolePermissionDto> rolePermissionPagination = this.authorityService.getRoleService()
		        .paginationRolePermissionByCode(roleVo.getRolePermission());

		final Map<String, Object> rolePermissionPaginationMap = Maps.newHashMap();

		rolePermissionPaginationMap.put(Constants.total.stringValue(), rolePermissionPagination.getTotalSize());
		rolePermissionPaginationMap.put(Constants.rows.stringValue(), rolePermissionPagination.getDataList());

		return rolePermissionPaginationMap;
	}

	/**
	 * 角色与许可：新增
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色与许可编辑视图路径
	 */
	@RequestMapping(value = { "rolePermission/new.html" }, method = RequestMethod.GET)
	public String rolePermissionNew(final RoleVo roleVo, final Model model) {
		model.addAttribute(RoleController.models.rolePermission.name(), roleVo.getRolePermission());

		return RoleController.Paths.ROLE_PERMISSIONNew.path();
	}

	/**
	 * 角色与许可：保存
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "rolePermission/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String rolePermissionSave(final RoleVo roleVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.rolePermissionValidator.validate(roleVo.getRolePermission(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.authorityService.getRoleService().saveRolePermissionByIdOrCode(roleVo.getRolePermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 角色与许可：更新
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "rolePermission/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> rolePermissionUpdate(final RoleVo roleVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getRoleService().updateRolePermissionByIds(roleVo.getRolePermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 角色与许可：验证
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "rolePermission/validationByCode.json" })
	@ResponseBody
	public Boolean rolePermissionValidationByCode(final RoleVo roleVo) {
		try {
			final int count = this.authorityService.getRoleService().readRolePermissionByCodeNqId(roleVo.getRolePermission());

			return (count < 1);
		} catch (final Exception e) {
			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 角色与许可：查看
	 * 
	 * @param roleVo
	 *            角色与许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色与许可查看编辑视图路径
	 */
	@RequestMapping(value = { "rolePermission/view.html" }, method = RequestMethod.GET)
	public String rolePermissionView(final RoleVo roleVo, final Model model) {
		final RolePermissionDto rolePermission = this.authorityService.getRoleService().findRolePermissionById(
		        roleVo.getRolePermission());

		model.addAttribute(RoleController.models.rolePermission.name(), rolePermission);

		return RoleController.Paths.ROLE_PERMISSIONView.path();
	}

	/**
	 * 角色：保存
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "role/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String roleSave(final RoleVo roleVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.roleValidator.validate(roleVo.getRole(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.authorityService.getRoleService().saveRoleByIdOrCode(roleVo.getRole());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 角色：更新
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "role/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> roleUpdate(final RoleVo roleVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getRoleService().updateRoleByIds(roleVo.getRole());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 角色：验证
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "role/validationByCode.json" })
	@ResponseBody
	public Boolean roleValidationByCode(final RoleVo roleVo) {
		try {
			final int count = this.authorityService.getRoleService().readRoleByCodeNqId(roleVo.getRole());

			return (count < 1);
		} catch (final Exception e) {
			if (RoleController.log.isDebugEnabled()) {
				RoleController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 角色：查看
	 * 
	 * @param roleVo
	 *            角色视图对象
	 * @param model
	 *            上下文映射
	 * @return 角色查看编辑视图路径
	 */
	@RequestMapping(value = { "role/view.html" }, method = RequestMethod.GET)
	public String roleView(final RoleVo roleVo, final Model model) {
		final RoleDto role = this.authorityService.getRoleService().findRoleById(roleVo.getRole());

		model.addAttribute(RoleController.models.role.name(), role);

		return RoleController.Paths.ROLEView.path();
	}
}
